package com.centit.framework.ip.templateFile.controller;

import com.alibaba.fastjson.JSONObject;
import com.centit.framework.ip.templateFile.po.OptStuffInfo;
import com.centit.framework.ip.templateFile.po.TemplateFile;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.centit.framework.ip.templateFile.service.OptStuffInfoManager;
import com.centit.framework.security.model.CentitUserDetails;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONArray; 
import com.centit.framework.common.JsonResultUtils;
import com.centit.framework.common.ResponseMapData;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.core.controller.BaseController;
import com.centit.support.database.utils.PageDesc;

/**
 * OptStuffInfo  Controller.
 * create by scaffold 2018-06-05 
 * @author 脚手架，改成开发者的名字
 * 流程与文书的映射关系表流程与文书的映射关系表   
*/


@Controller
@RequestMapping("/templateFile/optstuffinfo")
public class OptStuffInfoController  extends BaseController {
	private static final Log log = LogFactory.getLog(OptStuffInfoController.class);
	
	@Resource
	private OptStuffInfoManager optStuffInfoMag;	
	

    /**
     * 查询所有   流程与文书的映射关系表  列表
     *
     * @param field    json中只保存需要的属性名
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return {data:[]}
     */
    @RequestMapping(method = RequestMethod.GET)
    public void list(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> searchColumn = convertSearchColumn(request);        
        
        JSONArray jsonArrayObjects = optStuffInfoMag.listObjectsAsJson( searchColumn, pageDesc);
         
        if (null == pageDesc) {
            JsonResultUtils.writeSingleDataJson(jsonArrayObjects, response);
            return;
        }
        
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);

        JsonResultUtils.writeResponseDataAsJson(resData, response);
    }
    
    /**
     * 查询单个  流程与文书的映射关系表 
	
	 * @param stuffid  STUFFID
     *  
     * 
     * @param response    {@link HttpServletResponse}
     * @return {data:{}}
     */
    @RequestMapping(value = "/{stuffid}", method = {RequestMethod.GET})
    public void getOptStuffInfo(@PathVariable String stuffid, HttpServletResponse response) {
    	
    	OptStuffInfo optStuffInfo =     			
    			optStuffInfoMag.getObjectById( stuffid);
        
        JsonResultUtils.writeSingleDataJson(optStuffInfo, response);
    }
    
    /**
     * 新增 流程与文书的映射关系表，业务只有新增的时候可用此方法，如有修改可用下面 新增或保存合并的方法
     *
     * @param optStuffInfo  {@link OptStuffInfo}
     * @return
     */
    @RequestMapping(method = {RequestMethod.POST})
    public void createOptStuffInfo(@Valid OptStuffInfo optStuffInfo, HttpServletResponse response) {
    	 optStuffInfoMag.saveNewObject(optStuffInfo);
        JsonResultUtils.writeSingleDataJson("操作成功",response);
    }

    /**
     * 删除单个  流程与文书的映射关系表 
	
	 * @param stuffid  STUFFID
     */
    @RequestMapping(value = "/{stuffid}", method = {RequestMethod.DELETE})
    public void deleteOptStuffInfo(@PathVariable String stuffid, HttpServletResponse response) {
    	
    	optStuffInfoMag.deleteObjectById( stuffid);
        
        JsonResultUtils.writeSingleDataJson("操作成功",response);
    } 
    
    /**
     * 新增或保存 流程与文书的映射关系表 
    
	 * @param stuffid  STUFFID
	 * @param optStuffInfo  {@link OptStuffInfo}
     * @param response    {@link HttpServletResponse}
     */
    @RequestMapping(value = "/{stuffid}", method = {RequestMethod.PUT})
    public void updateOptStuffInfo(@PathVariable String stuffid, 
    	@Valid OptStuffInfo optStuffInfo, HttpServletResponse response) {
    	
    	
    	OptStuffInfo dbOptStuffInfo  =     			
    			optStuffInfoMag.getObjectById( stuffid);
        
        

        if (null != dbOptStuffInfo) {//如果数据库数据存在，则是更新操作
        	dbOptStuffInfo .copyNotNullProperty(optStuffInfo);//赋值页面不为空的值，小心页面空的字符串或者改写copyNotNullProperty方法，根据自己业务需要
        	optStuffInfoMag.mergeObject(dbOptStuffInfo);
        } else {
             optStuffInfoMag.saveNewObject(optStuffInfo);//新增,注意主键赋值 UuidUtil.getTimeBasedUuid()，填写自己的业务时间，业务操作人等信息
        }

        JsonResultUtils.writeSingleDataJson("操作成功",response);
    }
    /**
     * 跳转到金格编辑页面
     *
     * @return
     * @throws UnsupportedEncodingException 
     */
    @RequestMapping(value = "/toDocumentEdit",method = {RequestMethod.GET})
    public void toDocumentEdit(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String mSubject = null;
        String mStatus = null;
        String mFileName = null;
        String mFileDate = null;
        String mHTMLPath = "";
        String mDisabled = "";
        String mDisabledSave = "";
        String mWord = "";
        String mExcel = "";
        String infoId = request.getParameter("infoId");
        //流程步骤或者模块简写(保留属性，以后将逐渐取消，或者用flowPhase代替)
        String flowStep = request.getParameter("flowStep");
        flowStep = (flowStep == null ? "" : flowStep);
        String archiveType = request.getParameter("archiveType");
        /**
         *文号规则
         */
        String codeCode = request.getParameter("codeCode");
        /**
         *机构代码
         */
        String primaryUnit = request.getParameter("primaryUnit");
        /**
         *节点code
         */
        String nodeCode = request.getParameter("nodeCode");

        String fileid = request.getParameter("fileid");
        String filePath = "";
        String userName = request.getParameter("UserName");
        userName =  java.net.URLDecoder.decode(userName,"UTF-8");

        //文书类型
        String fileStyle = request.getParameter("fileStyle");
        if (fileStyle == null || fileStyle == "")
            fileStyle = "1";
        //自动获取OfficeServer和OCX文件完整URL路径
        String mHttpUrlName = request.getRequestURI();
        String mScriptName = request.getServletPath();

        //参数描述 ：fileType 文件分类-默认1 ---- 1：格式文书 2：申请附件 3：办理附件 4：证据（处罚平台用）
        String mServerName = "OfficeServer?fileType=" + fileStyle
                + "&archiveType=" + archiveType + "&flowStep=" + flowStep
                + "&codeCode=" + codeCode + "&primaryUnit=" + primaryUnit
                + "&nodeCode=" + nodeCode;
        String serverURI = "http://"
                + request.getServerName()
                + ":"
                + request.getServerPort()
                + mHttpUrlName.substring(0,
                mHttpUrlName.lastIndexOf(mScriptName)) + "/";
        String mServerUrl = serverURI + mServerName;//取得OfficeServer文件的完整URL
        String mHttpUrl = "http://"
                + request.getServerName()
                + ":"
                + request.getServerPort()
                + mHttpUrlName.substring(0,
                mHttpUrlName.lastIndexOf(mScriptName)) + "/";

        String mRecordID = request.getParameter("RecordID");
	/*
	 *模版编号
	 */
        String mTemplate = request.getParameter("Template");
        //System.out.println("111111"+mTemplate);
        //获取模板id（文件多次调用id）
        String mTemplateId = request.getParameter("mTemplateId");
        //强行制定.doc类型
        String mFileType = ".doc";
        String mEditType = request.getParameter("EditType");
        String mShowType = request.getParameter("ShowType");
        String mNeedBookMark = request.getParameter("NeedBookMark");

        //设置编号初始值
	/* if (mRecordID == "") {
		java.util.Date dt=new java.util.Date();
        long lg=dt.getTime();
        Long ld=new Long(lg);
        mRecordID=ld.toString();
	} */

        //设置编辑状态初始值
        if (mEditType == null || mEditType == "") {
            mEditType = "1,1";
        }

        //设置显示模式初始值
        if (mShowType == null || mShowType == "") {
            mShowType = "1";
        }

        //设置文档类型初始值
        if (mFileType == null || mFileType == "") {
            mFileType = ".doc";
        }

        //设置模板初始值
        if (mTemplate == null || mTemplate.trim().equals("")) {
            mTemplate = "OLD_DOC";//领导要求默认OLD_DOC
        }

        String fileName = request.getParameter("fileName");
        if(StringUtils.isBlank(fileName)){
            fileName="发文拟稿正文";
        }else{
            try {
                fileName = URLDecoder.decode(fileName, "utf-8");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        fileName+=".doc";
       //获取文档
        if (mEditType == "0,0") {
            mDisabled = "disabled";
            mDisabledSave = "disabled";
        } else {
            mDisabled = "";
        }

        mFileName = mRecordID + mFileType; //取得完整的文档名称
        if (mFileType.equalsIgnoreCase(".doc")
                || mFileType.equalsIgnoreCase(".wps")) {
            mWord = "";
            mExcel = "disabled";
        } else if (mFileType == ".xls") {
            mWord = "disabled";
            mExcel = "";
        } else {
            mDisabled = "disabled";
        }
        JSONObject docJson=new JSONObject();
        docJson.put("flowStep",flowStep);
        docJson.put("nodeCode",nodeCode);
        docJson.put("fileid",fileid);
       // TemplateFile templateFile=templateFileMag.getObjectById(mRecordID);
        docJson.put("mServerUrl",mServerUrl);
        docJson.put("mRecordID",mRecordID);
        docJson.put("mTemplate",mTemplate);
        docJson.put("mTemplateId",mTemplateId);
        docJson.put("mFileName",mFileName);
        docJson.put("fileName",fileName);
        docJson.put("mFileType",mFileType);
        docJson.put("mEditType",mEditType);
        docJson.put("mUserName",userName);
        docJson.put("infoId",infoId);
        request.setAttribute("docJson",docJson);
        try {
            request.getRequestDispatcher("/modules/templatefile/documentEdit.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
